package com.lagou.module01.servlet;

import com.lagou.module01.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "StudentRemoveServlet", urlPatterns = "/studentRemove")
public class StudentRemoveServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符编码为UTF-8
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //获取请求中的学号参数
        String sid = request.getParameter("sid");
        Integer studentId = -1;
        if (null != sid) {
            studentId = Integer.valueOf(sid);
        }

        //调用StudentService类的StudentRemove方法
        StudentService studentService = new StudentService();
        int i = studentService.StudentRemove(studentId);

        // 通过输出流向前台页面展示处理结果，然后重新请求一次数据
        PrintWriter writer = response.getWriter();
        // 获取模块名称
        String contextPath = this.getServletContext().getContextPath();
        // 拼接请求路径
        String hrefPath = contextPath + "/findUserByPage";
        if(0 != i) {
            writer.print("<script>alert('删除学生成功！'); location.href='" + hrefPath
                    + "';</script>");
        }else{
            writer.print("<script>alert('删除学生失败！'); location.href='" + hrefPath
                    + "';</script>");
        }
        writer.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
